<template>
  <div class="case-list">
    <!-- 搜索区域 -->
    <div class="search-section">
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="案件编号">
          <el-input
            v-model="searchForm.caseNumber"
            placeholder="请输入案件编号"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="当事人">
          <el-input
            v-model="searchForm.parties"
            placeholder="请输入当事人信息"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="审理法院">
          <el-input
            v-model="searchForm.court"
            placeholder="请输入审理法院"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="案件状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择案件状态"
            clearable
            style="width: 150px"
          >
            <el-option
              v-for="option in CASE_STATUS_OPTIONS"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作区域 -->
    <div class="action-section">
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        新增案件
      </el-button>
    </div>

    <!-- 表格区域 -->
    <div class="table-section">
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="caseNumber" label="案件编号" min-width="150" />
        <el-table-column prop="parties" label="当事人" min-width="200" show-overflow-tooltip />
        <el-table-column prop="court" label="审理法院" min-width="150" show-overflow-tooltip />
        <el-table-column prop="status" label="案件状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">
              {{ CASE_STATUS[row.status] }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="documentTitle" label="关联文档" min-width="200" show-overflow-tooltip />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="handleDetail(row)"
            >
              详情
            </el-button>
            <el-button
              type="success"
              size="small"
              :loading="editLoadingMap[row.id]"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页区域 -->
    <div class="pagination-section">
      <el-pagination
        v-model:current-page="pagination.pageNum"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <CaseForm
      v-model:visible="formVisible"
      v-model:case-data="currentCase"
      @refresh="fetchCaseList"
    />

    <!-- 详情对话框 -->
    <CaseDetail
      v-model:visible="detailVisible"
      :case-id="currentCaseId"
      @edit="handleEdit"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus } from '@element-plus/icons-vue'
import { getCasePage, deleteCase, getCaseDetail, CASE_STATUS_OPTIONS, CASE_STATUS } from '../../api/case'
import CaseForm from './components/CaseForm.vue'
import CaseDetail from './components/CaseDetail.vue'

// 搜索表单
const searchForm = reactive({
  caseNumber: '',
  parties: '',
  court: '',
  status: null
})

// 分页信息
const pagination = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 编辑按钮加载状态
const editLoadingMap = ref({})

// 对话框状态
const formVisible = ref(false)
const detailVisible = ref(false)
const currentCase = ref(null)
const currentCaseId = ref(null)

// 获取状态标签类型
const getStatusTagType = (status) => {
  const option = CASE_STATUS_OPTIONS.find(opt => opt.value === status)
  return option?.type || 'info'
}

// 获取案件列表
const fetchCaseList = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: pagination.pageNum,
      pageSize: pagination.pageSize,
      ...searchForm
    }
    
    // 过滤空值
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key]
      }
    })

    const response = await getCasePage(params)
    if (response.code === 200) {
      tableData.value = response.data.records
      pagination.total = response.data.total
    }
  } catch (error) {
    console.error('获取案件列表失败:', error)
    ElMessage.error('获取案件列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.pageNum = 1
  fetchCaseList()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    caseNumber: '',
    parties: '',
    court: '',
    status: null
  })
  pagination.pageNum = 1
  fetchCaseList()
}

// 新增
const handleAdd = () => {
  currentCase.value = null
  formVisible.value = true
}

// 编辑
const handleEdit = async (row) => {
  editLoadingMap.value[row.id] = true
  try {
    const response = await getCaseDetail(row.id)
    if (response.code === 200) {
      currentCase.value = response.data
      formVisible.value = true
    }
  } catch (error) {
    console.error('获取案件详情失败:', error)
    ElMessage.error('获取案件详情失败')
  } finally {
    editLoadingMap.value[row.id] = false
  }
}

// 详情
const handleDetail = (row) => {
  currentCaseId.value = row.id
  detailVisible.value = true
}

// 删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除案件"${row.caseNumber}"吗？`,
      '确认删除',
      {
        type: 'warning'
      }
    )

    const response = await deleteCase(row.id)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      fetchCaseList()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除案件失败:', error)
      ElMessage.error('删除案件失败')
    }
  }
}

// 分页大小改变
const handleSizeChange = () => {
  pagination.pageNum = 1
  fetchCaseList()
}

// 当前页改变
const handleCurrentChange = () => {
  fetchCaseList()
}

// 组件挂载时获取数据
onMounted(() => {
  fetchCaseList()
})
</script>

<style scoped>
.case-list {
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-section {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 6px;
}

.search-form {
  margin: 0;
}

.action-section {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-section {
  margin-bottom: 20px;
}

.pagination-section {
  display: flex;
  justify-content: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .case-list {
    padding: 10px;
  }
  
  .search-form {
    display: block;
  }
  
  .search-form .el-form-item {
    width: 100%;
    margin-bottom: 10px;
  }
  
  .search-form .el-input,
  .search-form .el-select {
    width: 100% !important;
  }
}
</style>
